var IS_LOGGED_IN = false;
var LOGIN_FORM = false;
var CONFIRM_REGISTRATION = false;


//facebook
var LOGGED_IN_FB = false; 
var FACEBOOK_RESPONSE = -1;


SpiderGame = function(){

        // game state vars.
        var PAUSE= false;
        var START = true;
        var GAME_OVER = false;
        var TREAT_GAME_OVER = false;
        var FREEZE = 0;
        var FREEZE_TIME = 200;
        var HELP = false;
        var REDRAW = true;
        var SENT_GAME_END_REQ = false;
        var HIGH_SCORE = false;
        
        
        
        var canvas;
        var context;
        
        var tokenImageObj;
        var dounatImageObj;
        var enemyImageObj;
        var fireballImageObj;
        var beerImageObj;
        
        var dounats;
        var dounatsAmount = 1;
        var dounatsCounter = 0;
        var foo = 0;
        
        var fireballs;
        var fireballsAmount = 1;
        
        var maxX;
        var minX = 0;
        var maxY;
        var minY;
                
        var myEnemy;
        var tokenSpace = 9/10;
        
        var mySpider;
        
        
        
        
        // sound vars
        var burpSound = new Audio("./sfx/burp.wav");
        var explosionSound = new Audio("./sfx/explosion.wav");
        var donutSound = new Audio("./sfx/woohoo.wav");
        

        
        
        init = function(){
        
	        mySpider = new Spider(0,100,15);		// HOMER's SPEED
	        myEnemy = new Enemy(0);
	                
	        REDRAW = true;
	        PAUSE= false;
	        HELP = false;
	        START = true;
	        
	        GAME_OVER = false;
	        SENT_GAME_END_REQ = false;
	        TREAT_GAME_OVER = false;
	        HIGH_SCORE = false;
            $("#arena").toggleClass("arenaRT");

	        
	        
	        
            if(!LOGGED_IN_FB || (LOGGED_IN_FB && !alreadyRegistered())){
            	toggle_visibility_block("#register");
            }
            
	        if(!LOGGED_IN_FB){
	        	toggle_visibility_block("#fbLogin");
	        	toggle_visibility_block("#login");
	        }
        
        }
        
        

        
        
        
                // ------function that executes token move------
        executeMove = function(e){
        	
        	
        	
        	 // to disable screen scrolling
                                
        
        
                // if the game is not on pause/start - read arrow-key events
                if(!START && !PAUSE && !HELP && !TREAT_GAME_OVER){
                	e.preventDefault();
                        if (e.keyCode == 37) {//left 
                        	
                                if(mySpider.x > minX) {
                                        mySpider.x -= mySpider.speed;
                                } else 
                                        return false;
                        }
                        if (e.keyCode == 38) { //up
                        	
                                if(mySpider.y > minY) {
                                        mySpider.y -= mySpider.speed;
                                } else 
                                        return false;
                        }
                        if (e.keyCode == 39) { //right
                        	
                                if(mySpider.x < maxX) {
                                        mySpider.x += mySpider.speed;
                                } else 
                                        return false;
                        }
                        if (e.keyCode == 40) { //down
                        	
                                if(mySpider.y < maxY) {
                                        mySpider.y += mySpider.speed;
                                } else 
                                        return false;
                        }
                }
                
                if ((e.keyCode == 32) && !HELP && TREAT_GAME_OVER && HIGH_SCORE && !LOGIN_FORM && !CONFIRM_REGISTRATION){
                	e.preventDefault();
                	init();
                    this.newGame();
                        
                        
                }
                // if space is pressed switch to pause
                if ((e.keyCode == 32) && !HELP && !TREAT_GAME_OVER && !LOGIN_FORM && !CONFIRM_REGISTRATION){
                	e.preventDefault();
                        if (START){
                        	toggle_visibility_off("#login");
                        	toggle_visibility_off("#register");
                        	toggle_visibility_off("#fbLogin");
                                START = false;
                                REDRAW = true;
                                return;
                        }
                        if (PAUSE){
                                REDRAW = true;
                        }
                        PAUSE = !PAUSE;       
                }
                //if 'h' or 'H' were pressed flip the HELP switch (not while the game is paused)
                if ((!PAUSE) && (!START) && (!HIGH_SCORE) && (!TREAT_GAME_OVER) && (e.keyCode == 72 || e.keyCode == 104) ){
                	e.preventDefault();
                        if (HELP){
                                REDRAW = true;
                        }
                        HELP = !HELP;
                }
        }
        
        
        
        
        /* ----------------------- class Dounat-----------------  */
        Dounat = function(xLoc, yLoc) {
                this.x = xLoc; 
                this.y = yLoc; 
                this.valid = 1;
                this.id = 1;
        }
        
        Beer = function(xLoc, yLoc) {
                this.x = xLoc; 
                this.y = yLoc; 
                this.valid = 1;
                this.id = 2;
        }

        /* ----------------------- class Fireball-----------------  */
        Fireball = function(xLoc, yLoc) {
                this.x = xLoc; 
                this.y = yLoc;
                this.dx = 3;
                this.dy = 3;
                this.valid = 1;
                this.dir = 1;
                
                        this.move = function(){
                                if(this.valid==1){

                                                this.y -= (this.dy + 2);

                                                if ((this.x + fireballImageObj.width > canvas.width) || (this.x < 0)){
                                                        this.dir = this.dir * (-1);
                                                }
                                                this.x += this.dx*this.dir;
                                                if(this.y <= minY){
                                                        this.valid = 0;
                                                }
                                }
                                else {
                                if(FREEZE == 0){
                                                this.dir = (function(){
                                                        if (Math.random() < 0.5){
                                                                return -1;
                                                        }
                                                        else {
                                                                return 1;
                                                        }
                                                })();
                                                this.x = myEnemy.x;
                                                this.y = myEnemy.y-fireballImageObj.height-10;
                                                this.dx = Math.floor(Math.random()*1) + 3;  //give the new fireball a new dx
                                                this.dy = Math.floor(Math.random()*1) + 3;      // give the new fireball a new dy
                                                this.valid = 1;
                                        }
                                }
                                return;
                        }
                
        }
        
        /* ----------------------- class Enemy-----------------  */
        Enemy = function(xLoc) {
                this.x = xLoc;
                this.y = canvas.height * 9/10;
                this.dir = 1;//the direction enemy is headed (left/right)
        }
        
        /* this function is made to detect collision between an optional dounat quardinate x,y and an existing dounat*/
        colideWithOthers = function(x,y){
                for (i=0;i<dounatsAmount;i++) {
                        if (dounats[i]!=null){
                                if ((x >= dounats[i].x) && (x <= dounats[i].x + dounatImageObj.width) && 
                                        (y >= dounats[i].y) && (y <= dounats[i].y + dounatImageObj.height))return true;
                        
                                if ((dounats[i].x >= x) && (dounats[i].x <= x + dounatImageObj.width) && 
                                        (dounats[i].y >= y) && (dounats[i].y <= y + dounatImageObj.height))return true;
                
                                if ((x + dounatImageObj.width >= dounats[i].x) && (x + dounatImageObj.width <= dounats[i].x + dounatImageObj.width) && 
                                        (y >= dounats[i].y) && (y <= dounats[i].y + dounatImageObj.height))return true;
                        
                                if ((dounats[i].x + dounatImageObj.width >= x) && (dounats[i].x + dounatImageObj.width <= x + dounatImageObj.width) && 
                                        (dounats[i].y >= y) && (dounats[i].y <= y + dounatImageObj.height))return true;
                        }
                }
                return false;
        }
        
        
        
        /* this function is made to detect collision between two objects*/
        colide = function(o1,imo1,o2,imo2){
        
                if ((o1.x >= o2.x) && (o1.x <= o2.x + imo2.width) && 
                                (o1.y >= o2.y) && (o1.y <= o2.y + imo2.height)) return true;
                if ((o2.x >= o1.x) && (o2.x <= o1.x + imo1.width) && 
                                (o2.y >= o1.y) && (o2.y <= o1.y + imo1.height)) return true;
                if ((o1.x + imo1.width >= o2.x) && (o1.x + imo1.width<= o2.x + imo2.width) && 
                                (o1.y >= o2.y) && (o1.y <= o2.y + imo2.height)) return true;
                if ((o2.x + imo2.width >= o1.x) && (o2.x + imo2.width<= o1.x + imo1.width) && 
                                (o2.y >= o1.y) && (o2.y <= o1.y + imo1.height)) return true;
                return false;
                
        }
        
        /* ----------------------- class Spider-----------------  */
        Spider = function(xLoc, yLoc, speed) {
                this.x = xLoc; 
                this.y = yLoc;  
                this.speed = speed;
                this.score = 0;
                this.lives = 1;
                this.bonus = 0;
        }       
                
        checkForFireballs = function(){ //check if token was shot
                
                for (i=0;i<fireballsAmount; i++) {
                        if(fireballs[i]!=null && fireballs[i].valid==1){
                                if (colide(mySpider,tokenImageObj,fireballs[i],fireballImageObj)){
                                        explosionSound.play();
                                        mySpider.lives--;
                                        mySpider.x = 0;
                                        mySpider.y = 100;
                                        
                                        if (mySpider.lives == 0) {
                                                GAME_OVER = true;
                                        }
                                        
                                        
                                        fireballs[i].valid = 0;
                                        break;
                                }
                        }
                }
        }
        
        checkForDounats = function(){//check if eat dounat
                
                $("#debug").html(mySpider.x+" "+mySpider.y);
                for (i=0;i<dounatsAmount; i++) {
                        if(dounats[i]!=null && dounats[i].valid==1){
                                if (colide(mySpider,tokenImageObj,dounats[i],dounatImageObj)){
                                        
                                        
                                        if(dounats[i].id==1){
	                                        donutSound.play();
	                                        mySpider.score++;
	                                        
	                                        
	                                        
	                                        mySpider.bonus++;
	                                        
	                                        if (mySpider.bonus == 10){
	                                        
		                                        mySpider.lives++;
		                                        mySpider.bonus=0;
	                                        }
	                                        
                                        }
                                        else{
	                                        burpSound.play();
	                                        FREEZE = FREEZE_TIME;
                                        }
                                        
                                        dounats[i].valid = 0;
                                        dounatsCounter--;
                                        break;
                                }
                        }
                }
        }
        
        //adds dounats to board
        addDounats = function(){
                if(dounatsCounter < dounatsAmount){
                
                
                        (function addDounat() {
                                
                                for (i=0; i<dounatsAmount;i++){
                                        
                                                collision = true;
                                                do {
                                                		var randomx=Math.floor(Math.random()*(canvas.width - dounatImageObj.width)) - 1;        
                                                		var randomy=Math.floor(Math.random()* (canvas.height * 8*(1-tokenSpace) - dounatImageObj.height-10) + canvas.height*(1-tokenSpace)+10);
                                                        collision = colideWithOthers(randomx,randomy) ;
                                                }while(collision == true);
                                                var randomGood = Math.random();
                                                if(randomGood<0.9){
                                                var dounat = new Dounat(randomx,randomy);
                                                addObjectToArr(dounat,dounats);
                                                }
                                                else{
                                                var beer = new Beer(randomx,randomy);
                                                addObjectToArr(beer,dounats);
                                                
                                                }
                                                dounatsCounter++;
                                        
                                }       
                        }());
                }
        }
        
        
        //adds fireballs to board

        addFireball = function(x,y){
                
                var fireball = new Fireball(x,y-fireballImageObj.height);
                addObjectToArr(fireball,fireballs);
        }
        
        
        clearArena = function(){
                //clear top 
                context.clearRect(0,0,canvas.width,canvas.height * (1-tokenSpace) - 1);
                // clear middle
                context.clearRect(0,canvas.height * (1-tokenSpace) + 2, canvas.width, (canvas.height * tokenSpace) - 50);
                //clear bottom
                context.clearRect(0,canvas.height * tokenSpace + 2,canvas.width,canvas.height);
        }
        
        drawBorders = function(){
                //DRAW GAME LINES
                //upper line
                context.moveTo(0, canvas.height * (1-tokenSpace) + 1 );
                context.lineTo(canvas.width,canvas.height * (1-tokenSpace) + 1 );
                context.stroke();
                //lower line
                context.moveTo(0,canvas.height * tokenSpace - 1);
                context.lineTo(canvas.width,canvas.height * tokenSpace - 1);
                context.stroke();
        }
        
        DrawHighScore = function(JSONdataRT){
        	
        	HIGH_SCORE = true;
        	clearForm(0);
                context.clearRect(0,0,canvas.width,canvas.width,canvas.height);

                $("#arena").toggleClass("arenaRT");
                context.fillStyle    = 'white';
                context.font         =  'italic bold 1em sans-serif';
                var x = canvas.width/8.5;
                var y = canvas.height/5.5;
               
                
            
               /* {name: homer,
                   score: 30,
                   fbID: 73737373}*/
               
                var pos = 1;
                for (var element in JSONdataRT) {
                	
                	
                		if (pos>5) break;
                		
                		var name = JSONdataRT[element]['name'];
                		var score = JSONdataRT[element]['score'];
                		
                		
                		
                		var fbid = JSONdataRT[element]['fbID'];
                		
                		
                		if (fbid!="invalid"){
                			
                			fbUserImageObj = new Image();
                			fbUserImageObj.src = "http://graph.facebook.com/" + fbid + "/picture";
                			
                			fbUserImageObj.onLoad = drawFBuser(context,pos,name,x,y,score,fbUserImageObj);
                		}
                		
                		
                		pos++;
                	
                	
                }
                var pos = 1;
                for (var element in JSONdataRT) {
                	
                	
            		if (pos>5) break;
            		
            		var name = JSONdataRT[element]['name'];
            		var score = JSONdataRT[element]['score'];
            		var fbid = JSONdataRT[element]['fbID'];
            		
            		
            		if (fbid!="invalid"){
            			
            			
            			
            		}
            		
            		else{
            			context.fillText(pos+".  " + name, x, y + pos * 60);//drawing it and it's value(the score)
                		context.fillText(score, x+340, y + pos * 60);
            		}
            		pos++;
            	
            	
            }
                //back to default
                context.fillStyle    = 'black';
                context.font         = 'bold 1em sans-serif';
        }
         
        
       

        /*main functions of SpiderGame*/
return {
        /* this function initializes the spider object, the board,  */
        newGame: function(){
                canvas = document.getElementById("arena");
                context = canvas.getContext("2d");
                
                drawBorders();
                
                // IMAGES
                tokenImageObj = new Image();
                tokenImageObj.src = "images/homer.gif";
                dounatImageObj = new Image();
                dounatImageObj.src = "images/dounat.gif";
                beerImageObj = new Image();
                beerImageObj.src = "images/beer1.gif";
                enemyImageObj = new Image();
                enemyImageObj.src = "images/aliens.gif";
                fireballImageObj = new Image();
                fireballImageObj.src = "images/fireball.gif";
                pauseImage = new Image();
                pauseImage.src = "images/pause.jpg";
                startImage = new Image();
                startImage.src = "images/start.gif";
                HSImageObj = new Image();
                HSImageObj.src = "images/RTbackground.jpg";
                gameOverImage = new Image();
                gameOverImage.src = "images/gameOver.gif";
                helpImage = new Image();
                helpImage.src = "images/instructions.png";
                tokenFaceImageObj = new Image();
                tokenFaceImageObj.src = "images/homer_face.png";
                
                
                mySpider = new Spider(0,100,15);	// HOMER'S SPEED - FIRST GAME
                
                
                myEnemy = new Enemy(0);
                
                
                dounats = new Array(dounatsAmount);
                fireballs = new Array(fireballsAmount);
                
                

                tokenImageObj.onload = function(){
                        maxX = canvas.width - tokenImageObj.width-1;
                        maxY = (canvas.height * tokenSpace) - tokenImageObj.height - 15; 
                        minY = (canvas.height * (1-tokenSpace)) + 15; 
             };
              
                var bscore = readCookie("best-score");
                var uname = readCookie("nick");
                
                
        },
        
        getSpider: function(){
        	return mySpider;	
        },

        /* the heart of the game - this function runs the event listeners in the game*/ 
        run: function(){
                     
                // catch a key-down event
                $(document).keydown(function(e){
                        executeMove(e);
                });
                                
                for(i=0;i<fireballsAmount;i++)
                addFireball(myEnemy.x,myEnemy.y-50);
                
                
                
                
        },
        
        draw: function(){
                
                //redraw the lines if we had a pause/start/help/end-game screen
                if (REDRAW){
                        context.clearRect(0,0,canvas.width,canvas.height);      
                        drawBorders();
                        REDRAW = false;
                }
                else {
                        clearArena();
                }
                
                //game stats-text
                context.font = "bold 12px sans-serif";
                context.fillText("SCORE: " + mySpider.score, canvas.width/10, canvas.height*(1-tokenSpace)/2);
                context.fillText("LIVES: ", canvas.width*3/10, canvas.height*(1-tokenSpace)/2);
                for(i=1;i<=mySpider.lives;i++){
                context.drawImage(tokenFaceImageObj, canvas.width*3/10 + (tokenFaceImageObj.width + 1)  * i + 30, canvas.height*(1-tokenSpace)/2 - tokenFaceImageObj.height / 2);               
                }
                
                //draw tokens
                context.drawImage(tokenImageObj, mySpider.x, mySpider.y);
                context.drawImage(enemyImageObj, myEnemy.x, myEnemy.y);
                
                dounats.forEach(function(dounat){
                        if(dounat.valid==1){
                                if(dounat.id==1){
                                context.drawImage(dounatImageObj, dounat.x, dounat.y);
                                }
                                else{
                                context.drawImage(beerImageObj, dounat.x, dounat.y);
                                }
                        }
                });

                        

                fireballs.forEach(function(fireball){
                        if(fireball.valid==1){
                                context.drawImage(fireballImageObj, fireball.x, fireball.y);
                        }
                });
        
        
        },

        update: function(){
                addDounats();
                
                // update fireballs:    

                fireballs.forEach(function(fireball){
                        fireball.move();        
                });
            if(FREEZE == 0){            

                
                // update enemy:
                if(myEnemy.x >= canvas.width - 50){//this.imageWidth
                        myEnemy.dir = -1;
                }
                if(myEnemy.x <= 1){
                        myEnemy.dir = 1;
                }
                                                
                myEnemy.x += myEnemy.dir;
                
                }
                else FREEZE--;
                checkForFireballs();
                
                checkForDounats();

        },
        pauseGame: function(){
                context.clearRect(0,0,canvas.width,canvas.height);
                context.drawImage(pauseImage, 0,canvas.height/4);
        },
        isPaused: function(){
                return PAUSE;
        },
        startGame: function(){
                context.clearRect(0,0,canvas.width,canvas.height);
                context.drawImage(startImage, 0,0);
                
                if(!LOGGED_IN_FB){       
                	toggle_visibility_block("#fbLogin");
                }
                var name = readCookie("nick");
                var bestscore = readCookie("best-score"); 
                if (bestscore != null){
                        context.font = "bold 12px sans-serif";
                        context.fillText("Best Score: "+ bestscore, canvas.width*1/100, canvas.height*(1-tokenSpace));
                        if (name == null){
                                name = "Anonymous";
                        }
                        context.font = "bold 12px sans-serif";
                        context.fillText("Name: " + name, canvas.width/100, canvas.height*(1-tokenSpace)/2);    
                }               
        },
        isStart: function(){
                return START;
        },

        isGameOver: function(){
                return GAME_OVER;
        },
        isTreatGameOver: function(){
                return TREAT_GAME_OVER;
        },
        
        treatGameOver: function(){
        	
                
            if(!SENT_GAME_END_REQ){
            	
            	if(($("#ScoreSubmitForm").css("display"))=="none"){
                    	toggle_visibility_block("#ScoreSubmitForm");//simply turning the form to visible using this function
            	}
            	SENT_GAME_END_REQ = true;
            	
                    if(IS_LOGGED_IN || LOGGED_IN_FB){
                    	
                    	toggle_visibility_off("#uname");
                    	$("#regFormText").html("Would you like to submit your score?");
                    }
                    else{
                    	toggle_visibility("#uname");//TODO: replace with facebook registration shit
                    	$("#regFormText").html("If you want you can sign up in main page,</br>meanwhile you may enter a nickname to submit your score");

                    }
                    
                    }
    },
        gameOver: function(){
        	
        	
        	
                context.clearRect(0,0,canvas.width,canvas.height);
                var d = "";
                if (mySpider.score!=1){
                        d="s";
                }
                
                $("#scoreReport").html("You have eaten " + mySpider.score + " donut" + d + "!");
                
                
                /*assignment 2 flow start*/
                
                    GAME_OVER = false;
                    TREAT_GAME_OVER = true;
                        
                
                

                
                
        },
        isGameHelp: function(){
                return HELP;
        },
        gameHelp: function(){
                context.clearRect(0,0,canvas.width,canvas.height);
                context.drawImage(helpImage, 0, 0);
        }
};

};






/* beginning of flow*/
$(document).ready(function(){
	
   

   var game = new SpiderGame();
        
                game.newGame();
                game.run();
                
                
                setInterval(function() {
                        
                                if (game.isGameOver()){
                                        game.gameOver();
                                }
                                if (game.isTreatGameOver()){
                                        game.treatGameOver();
                                }
                                else if (game.isStart()){
                                        game.startGame();
                                }
                                else if (game.isPaused()){
                                        game.pauseGame();
                                }
                                else if (game.isGameHelp()){
                                        game.gameHelp();
                                }
                                else {//Regular flow
                                        game.draw();
                                        game.update();
                                }
                        },30);
                
                
                //form listeners
                $("#confirmationOK").click(function() {//recognizing a click event on submit and running another function
                	toggle_visibility_off("#confirmationMessage");
                	CONFIRM_REGISTRATION = false;
                });
                
                $("#FBRegisterButton").click(function() {
                if(($("#fbregisterForm").css("display"))=="none"  && !IS_LOGGED_IN && !(LOGGED_IN_FB &&  alreadyRegistered())){
                	
                	
                	if(LOGGED_IN_FB){
                		$("#fbregisterForm").modal();
                	}
                	else{
                		$("#registerForm").modal();
                		
                	}
                	}
                });
                
                
                $("#registerFormSubmit").click(function() {//recognizing a click event on submit and running another function
                	handleForm(game.getSpider().score,true);
                });
                
                $("#noThanks").click(function() {//recognizing a click event on submit and running another function
                	handleForm(game.getSpider().score,false);
                    });
                
                $("#fbTimeLineButton").click(function(){
                	$("#fbTimeLine").modal();
                	
                }
                )
                
                $("#login").click(function() {//recognizing a click event on login
                	if(($("#loginHref").html())=="log in"){
	                	
                		
	                	LOGIN_FORM = true;
                		
                		
	                	if($("#LoginForm").css("display") == "none"){
	                		toggle_visibility("#LoginForm");
	                		
	                	}
                	}
                	else if(($("#loginHref").html())=="log out"){
                		LOGIN_FORM = false;
                		IS_LOGGED_IN = false;
                		$("#loginHref").html("log in");
	                	eraseCookie("nick");
	                	eraseCookie("best-score");
	                		
	                	
                	}
                });
                $("#IdontWantToLogin").click(function() {//recognizing a click event on login
                	toggle_visibility_off("#LoginForm");
                	clearForm(1);
                	LOGIN_FORM = false;
                	
                });
                $("#loginFormSubmit").click(function() {//recognizing a click event on login
                	handleLoginForm();

                });
                
        
});

handleForm = function(score,sign){
	//alert(FACEBOOK_RESPONSE.name);
	//alert(FACEBOOK_RESPONSE.id);
	
	var prevScore = readCookie("best-score");
	var prevNick = readCookie("nick");
	

	if(!LOGGED_IN_FB){
		formSendJson(score,sign);
	}
	else{
		formSendJsonFB(score,sign);
	}

	var currScore = readCookie("best-score");
	var currNick = readCookie("nick");
	
    if((currNick == "") || (currNick == prevNick)){
		if((prevScore != null) && prevScore > currScore){
			createCookie("best-score", prevScore, 365);
		}//else the server already set the score cookie
    }
    if(currNick == ""){
    	if(prevNick!=null){
    		createCookie("nick", prevNick, 365);
    	}
    	else{
    		createCookie("nick", "Anonymous", 365);

    	}
    }
}

handleLoginForm = function(){   	
	formSendJsonLogin();
}


formSendJsonLogin = function(){
	var frm;
	var url;
	
	frm = document.forms[1]; //this is the registration form
 	url = "/Login.do";
 	 
 	var nick =  frm.elements["nick"].value;
    var email =  frm.elements["email"].value;
    var password =  frm.elements["password"].value;
    
    
    if (nick=="" || email=="" || password==""){
    	$("#loginFormError").html("You must fill in all fields!");
		return;
      }
      else $("#loginFormError").html("");
      
    
    var dat;
    dat =  {
            name: nick,
            email: email,
            password: password
        }
    
    var request = new XMLHttpRequest();
    request.open("POST", url, false); //the false indicates we want this to be sync, meaning we wait for an answer from the server
    
   
    	request.onreadystatechange = function(){  //this is used to listen for changes in the request's status and act accordingly
    		
    		var JSONdataRT = eval("(" + request.responseText + ")");//the way to get the json from the string sent by the servlet
	        var error = JSONdataRT["error"];
	        if (error != null){
	        	$("#loginFormError").html(error);
	        }
	        else{
	        		
		        	$("#loginFormError").html("");
		        	IS_LOGGED_IN = true;
		        	$("#loginHref").html("log out");
		        	LOGIN_FORM = false;
		        	toggle_visibility_off("#LoginForm");
		        	var name = JSONdataRT["nick"];
		        	var best_score = JSONdataRT["best-score"];
		        	
		        	createCookie("nick", name, 365);
		        	createCookie("best-score", best_score, 365);
		        	
		        	
		        	clearForm(1);//clear login form
		        	
	        }
	        
	    }
    
    request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//not important
    request.send(JSON.stringify(dat));//sending the httprequest with the JSON object in the body 
    
  }


//argument: the score the player just had
formSendJson = function(score,sign) {
	var frm;
	var url;
	
	frm = document.forms[0]; //this is the registration form
	url = "/donutrush1_0.do";

     
    //and it's inserted values
        var nick =  frm.elements["nick"].value;
        var email =  "";//frm.elements["email"].value;
        var password =  "";//frm.elements["password"].value;
        var password2 =  "";//frm.elements["password2"].value;
        var SignLevel = 0;
        
        if(sign){
      	  if (email!="" && password!=""){
      		  SignLevel = 2;
      	  }
      	  else SignLevel = 1;
        }
        
        if(!IS_LOGGED_IN && sign){
	          if (nick==""){
	        	$("#formError").html("Impossible to submit score with no User Name!");
				return;
	          }
//	          if ((email!="" && (password=="" || nick=="" || password2=="")) || (password!="" && (email=="" || nick=="" || password2=="")) ||(password2!="" && (email=="" || nick=="" || password==""))){
//	        	  $("#formError").html("Impossible to submit email/password/re-type password and leave other fields empty!");
//					return;
//	          }
//	          if (password != password2){
//	        	  $("#formError").html("Incompatibility between password and the re-type, try again");
//					return;
//	          }
	          else $("#formError").html("");
  	  }
       
        
	        	  
        

        var dat;
        if(!IS_LOGGED_IN){
        //this is the json - as simple as that, next I want to send this to the server
	          if(!sign){
	        	  nick = "";
	        	  email = "";
	        	  password = "";
	        	  SignLevel = 0;  
	          }
				    dat =  {
				            name: nick,
				            email: email,
				            password: password,
				            score: score,
				            loggedIn: 0,
				            SignLevel: SignLevel,
				            facebook:0
				        } 
        }
        else{//if logged in
      	  SignLevel = 1;
      	  if(!sign){
      		  SignLevel = 0; 
      	  }
      	  var cleanName = cleanCookie(readCookie("nick"));
      	  
      	  
      	  dat =  {
			            name: cleanName,
			            email: "",
			            password: "",
			            score: score,
			            loggedIn: 1,
			            SignLevel: SignLevel,
			            facebook:0
			            
			            
			        } 
        }
        
  
  //in web.xml '/donutrush1_0.do' is mapped to the servlet: donutrush1_0Servlet from the servelet package
  
  
  
  var request = new XMLHttpRequest();
  request.open("POST", url, false); //the false indicates we want this to be sync, meaning we wait for an answer from the server
  
 
	request.onreadystatechange = function(){  //this is used to listen for changes in the request's status and act accordingly
			var JSONdataRT = eval("(" + request.responseText + ")");//the way to get the json from the string sent by the servlet
	       
			if(JSONdataRT["error"]!=null){
				$("#formError").html(JSONdataRT["error"]);//already exists user with these details error
				return;
			}
			else{
				$("#formError").html("");
				if(SignLevel ==2){
					toggle_visibility("#confirmationMessage");
					CONFIRM_REGISTRATION = true;
				}
				
			}
			
			
			DrawHighScore(JSONdataRT);
	    
  }
 
  request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//not important
  request.send(JSON.stringify(dat));//sending the httprequest with the JSON object in the body 
  
}  


//argument: the score the player just had
formSendJsonFB = function(score,sign) {
	var frm;
	var url;
	
	frm = document.forms[0]; //this is the registration form
	url = "/donutrush1_0.do";

       
      //and it's inserted values
          var nick =  frm.elements["nick"].value;
          var email =  "";//frm.elements["email"].value;
          var password = "";// frm.elements["password"].value;
          var password2 = "";// frm.elements["password2"].value;
          var SignLevel = 0;
          
          if(sign){
        	  if (email!="" && password!=""){
        		  SignLevel = 2;
        	  }
        	  else SignLevel = 1;
          }
          
          if(!IS_LOGGED_IN && !LOGGED_IN_FB && sign){
	          if (nick==""){
	        	$("#formError").html("Impossible to submit score with no User Name!");
				return;
	          }
//	          if ((email!="" && (password=="" || nick=="" || password2=="")) || (password!="" && (email=="" || nick=="" || password2=="")) ||(password2!="" && (email=="" || nick=="" || password==""))){
//	        	  $("#formError").html("Impossible to submit email/password/re-type password and leave other fields empty!");
//					return;
//	          }
//	          if (password != password2){
//	        	  $("#formError").html("Incompatibility between password and the re-type, try again");
//					return;
//	          }
	          else $("#formError").html("");
    	  }
         
          
          	  
          

          var dat;
          if(!IS_LOGGED_IN){
          //this is the json - as simple as that, next I want to send this to the server
	          if(!sign){
	        	  nick = "";
	        	  email = "";
	        	  password = "";
	        	  SignLevel = 0;  //init
	          }
				    dat =  {
				    		
				            facebook: 1,
				            name: FACEBOOK_RESPONSE.name,
				            email: email,//FACEBOOK_RESPONSE.email,
				            facebookID: FACEBOOK_RESPONSE.id,
				            password: "facebook",
				            score: score,
				            loggedIn: 0,
				            SignLevel: SignLevel
				        } 
          }
          

          
          if (IS_LOGGED_IN){
        	  SignLevel = 1;
        	  if(!sign){
        		  SignLevel = 0; 
        	  }
        	  var cleanName = cleanCookie(readCookie("nick"));
        	  
	        	  dat =  {
	        			    facebook: 1,
				            name: FACEBOOK_RESPONSE.name,
				            email: email,//FACEBOOK_RESPONSE.email,
				            facebookID: FACEBOOK_RESPONSE.id,
				            password: "facebook",
				            score: score,
				            loggedIn: 1,
				            SignLevel: SignLevel
				            
				            
				        }
	        	  
        	  
        	  
        	  
          }
          
    
    //in web.xml '/donutrush1_0.do' is mapped to the servlet: donutrush1_0Servlet from the servelet package
    
    
          
          
    
    var request = new XMLHttpRequest();
    request.open("POST", url, false); //the false indicates we want this to be sync, meaning we wait for an answer from the server
    
   
	request.onreadystatechange = function(){  //this is used to listen for changes in the request's status and act accordingly
	
		var JSONdataRT = eval("(" + request.responseText + ")");//the way to get the json from the string sent by the servlet
	       
			if(JSONdataRT["error"]!=null){
				$("#formError").html(JSONdataRT["error"]);//already exists user with these details error
				return;
			}
			else{
				$("#formError").html("");
				if(SignLevel ==2 && !LOGGED_IN_FB){
					toggle_visibility("#confirmationMessage");
					CONFIRM_REGISTRATION = true;
				}
				
			}
			
			
			DrawHighScore(JSONdataRT);
	    
    }
   
    request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//not important
    request.send(JSON.stringify(dat));//sending the httprequest with the JSON object in the body 
    
  }



toggle_visibility = function(id) {
    var e = $(id);
    e.css('display','inline');
 }

toggle_visibility_block = function(id) {
    var e = $(id);
    e.css('display','block');
 }

toggle_visibility_off = function(id) {
    var e = $(id);
    e.css('display','none');
 }

clearForm = function(id){
	toggle_visibility_off("#ScoreSubmitForm");
	document.forms[id].elements["nick"].value = "";
	document.forms[id].elements["email"].value = "";
	document.forms[id].elements["password"].value = "";
	if (id==0){
		document.forms[id].elements["password2"].value = "";
		$("#formError").html("");
	}
	if(id==1){
		$("#loginFormError").html("");
	}
	
}



 /*adds o to arr in the first space which is not null*/
 addObjectToArr = function(o,arr){
        for(i=0;i<arr.length;i++){
        if (arr[i] == null || arr[i].valid == 0) {
                arr[i]=o;
                break;
        }
        }
}
 
 function createCookie(name,value,days) {
	 
     if (days) {
             var date = new Date();
             date.setTime(date.getTime()+(days*24*60*60*1000));
             var expires = "; expires="+date.toGMTString();
     }
     else var expires = "";
     
     document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	
     var nameEQ = name + "=";
     var ca = document.cookie.split(';');
     for(var i=0;i < ca.length;i++) {
             var c = ca[i];
             while (c.charAt(0)==' ') c = c.substring(1,c.length);
             if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
     }
     return null;
}

function eraseCookie(name) {
     createCookie(name,"",-1);
}




//
function alreadyRegistered(){
	 
	var result;
	//return true;
	var url;
	url = "/facebook_authorization.do";
	
	var dat =  {
	            facebookID: FACEBOOK_RESPONSE.id
	        }


//in web.xml '/donutrush1_0.do' is mapped to the servlet: donutrush1_0Servlet from the servelet package


var request = new XMLHttpRequest();
request.open("POST", url, false); //the false indicates we want this to be sync, meaning we wait for an answer from the server


request.onreadystatechange = function(){  //this is used to listen for changes in the request's status and act accordingly
	
	
	
	var JSONdataRT = eval("(" + request.responseText + ")");//the way to get the json from the string sent by the servlet
	
	
	if(JSONdataRT["result"]=="Denied"){
		result = false;
	}
	else{
		IS_LOGGED_IN = true;//TODO: check this
		result = true;
	}
	

}

request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//not important
request.send(JSON.stringify(dat));//sending the httprequest with the JSON object in the body 


return result;
}


function cleanCookie(value){

	if(value!=null){
		if(value.charAt(0)=='"' && value.charAt(value.length-1)=='"'){
			value = value.substring(1,value.length-1);
		}
	
	return value;
	}
	else return "";

}

function drawFBuser(context,pos,name,x,y,score,fbUserImageObj){
	//$("#userinfo").html('<img src='+ fbUserImageObj.src + '>');
	//$("#userinfo1").html('<img src="https://graph.facebook.com/623891203/picture">');
	context.fillText(pos+ ".                 " + name, x, y + pos * 60);//drawing it and it's value(the score)
	context.fillText(score, x+340, y + pos * 60);
	
	
	//I don't why but it won't draw the first time for only one drawImae so I added 2 more...
	context.drawImage(fbUserImageObj, x+20, y - 30 + pos * 60);
	context.drawImage(fbUserImageObj, x+20, y - 30 + pos * 60);
}